package com.yaoyanshe.trialfield.network.http

import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.coroutineScope

/**
 *<p>description:</p>
 *<p>created on: 2020/9/20 16:26</p>
 * @author tck
 * @version v1.3.0
 *
 */
open class BaseRepository {

    suspend fun <T : Any> apiCall(call: suspend () -> SytBaseResp<T>): SytBaseResp<T> {
        return call.invoke()
    }

    suspend fun <T : Any> safeApiCall(call: suspend () -> SytResult<T>, errorMessage: String = ""): SytResult<T> {
        return try {
            call()
        } catch (e: Exception) {
            if (errorMessage.isEmpty()) {
                SytResult.error(msg = e.message?:"")
            } else {
                SytResult.error(msg = errorMessage)
            }
        }
    }

    suspend fun <T : Any> executeResponse(response: SytBaseResp<T>, successBlock: (suspend CoroutineScope.() -> Unit)? = null,
                                          errorBlock: (suspend CoroutineScope.() -> Unit)? = null): SytResult<T> {
        return coroutineScope {
            if (response.status == 0) {
                successBlock?.let { it() }
                val data = response.data
                SytResult.success(data)
            } else {
                errorBlock?.let { it() }
                SytResult.error(code = response.subCode, msg = response.subMessage)
            }
        }
    }


}